<template>
  <div
    class="main-content"
    ref="main"
    id="main"
  >
    <el-button
      class="addbtn"
      :key="button.label"
      :type="button.type"
      :disabled="button.isDisabled"
      :size="button.size"
      @click="dialogAdd.visible = true"
      v-has="'ams:appCategoryManage:add'"
    >{{ button.label }}</el-button>
    <CommonTable
      :options="tableConfig.options"
      :columns="tableConfig.columns"
      :actions="tableConfig.actions"
      :data="tableData"
      @handleDragSort="handleDragSort"
    ></CommonTable>
    <CommonPagination
      :options="tablePagination.options"
      :dataSource="getTableData"
      class="keepdown"
    ></CommonPagination>

    <!-- 新增应用分类窗口 -->
    <el-dialog
      :title="$t('dialog.addAppCategory.title')"
      :visible.sync="dialogAdd.visible"
      width="400px"
      :close-on-click-modal="dialogAdd.closeOnClickModal"
      :close-on-press-escape="dialogAdd.closeOnPressEscape"
      append-to-body
      v-loading="dialogAdd.loading"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      @close="closeDialogAdd"
    >
      <el-form
        :model="dialogAdd.formData"
        :rules="addFormDataRules"
        ref="addCategory"
        label-position="right"
        label-width="80px"
      >
        <el-form-item
          :label="$t('dialog.addAppCategory.name')"
          prop="name"
        >
          <el-input
            size="medium"
            class="border-bottom"
            v-model="dialogAdd.formData.name"
            :placeholder="$t('placeholder.name')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('dialog.addAppCategory.icon')"
          prop="icon"
        >
          <el-input
            size="medium"
            class="border-bottom"
            v-model="dialogAdd.formData.icon"
            autocomplete="off"
            style="display: none"
          ></el-input>
          <div
            class="icon-box"
            @click="
              dialogIcon.type = 'add';
              dialogIcon.selected = dialogAdd.formData.icon;
              dialogIcon.visible = true;
            "
          >
            <div
              class="icon-content"
              v-if="dialogAdd.formData.icon != ''"
            >
              <i
                :class="dialogAdd.formData.icon"
                :style="iconColor.add"
              ></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('dialog.addAppCategory.iconColor')"
          prop="iconColor"
          class="special-form-item"
        >
          <el-color-picker
            v-model="dialogAdd.formData.iconColor"
            size="mini"
          ></el-color-picker>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="medium"
          @click="dialogAdd.visible = false"
        >{{ $t('btnText.cancel') }}</el-button>
        <el-button
          size="medium"
          type="primary"
          @click="submitAdd('addCategory')"
        >{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>

    <!-- 修改应用分类窗口 -->
    <el-dialog
      :title="$t('dialog.editAppCategory.title')"
      :visible.sync="dialogEdit.visible"
      width="400px"
      :close-on-click-modal="dialogEdit.closeOnClickModal"
      :close-on-press-escape="dialogEdit.closeOnPressEscape"
      append-to-body
      v-loading="dialogEdit.loading"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      @close="closeDialogEdit"
    >
      <el-form
        :model="dialogEdit.formData"
        :rules="editFormDataRules"
        ref="editCategory"
        label-position="right"
        label-width="80px"
      >
        <el-form-item
          :label="$t('dialog.editAppCategory.name')"
          prop="name"
        >
          <el-input
            size="medium"
            class="border-bottom"
            v-model="dialogEdit.formData.name"
            :placeholder="$t('placeholder.name')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('dialog.editAppCategory.icon')"
          prop="icon"
        >
          <el-input
            size="medium"
            class="border-bottom"
            v-model="dialogEdit.formData.icon"
            autocomplete="off"
            style="display: none"
          ></el-input>
          <div
            class="icon-box"
            @click="
              dialogIcon.type = 'edit';
              dialogIcon.selected = dialogEdit.formData.icon;
              dialogIcon.visible = true;
            "
          >
            <div
              class="icon-content"
              v-if="dialogEdit.formData.icon != ''"
            >
              <i
                :class="dialogEdit.formData.icon"
                :style="iconColor.edit"
              ></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          :label="$t('dialog.editAppCategory.iconColor')"
          prop="iconColor"
          class="special-form-item"
        >
          <el-color-picker
            v-model="dialogEdit.formData.iconColor"
            size="mini"
          ></el-color-picker>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="medium"
          @click="dialogEdit.visible = false"
        >{{ $t('btnText.cancel') }}</el-button>
        <el-button
          size="medium"
          type="primary"
          @click="submitEdit('editCategory')"
        >{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>

    <!-- 图标选择窗口 -->
    <el-dialog
      :title="$t('dialog.icons.title')"
      :visible.sync="dialogIcon.visible"
      width="600px"
      :close-on-click-modal="dialogIcon.closeOnClickModal"
      :close-on-press-escape="dialogIcon.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.5)"
      @close="closeDialogIcon"
    >
      <el-radio
        v-for="(item, index) in dialogIcon.data"
        :key="index"
        v-model="dialogIcon.selected"
        :label="item"
      ><i :class="item"></i></el-radio>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          size="medium"
          @click="dialogIcon.visible = false"
        >{{ $t('btnText.cancel') }}</el-button>
        <el-button
          size="medium"
          type="primary"
          @click="selectedIcon"
        >{{ $t('btnText.ok') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '../../components/componentCommon/CommonTableDraggable.vue';
import CommonPagination from '../../components/componentCommon/CommonPagination.vue';
import { getCategorys, categorySort, categoryDelete, categoryAdd, categoryEdit } from '../../api/api';
import { errorCode } from '@/utils/index';

export default {
  name: 'appCategoryManage',
  components: {
    CommonTable,
    CommonPagination
  },
  data() {
    return {
      tableMaxHeight: null,
      tableAllData: [],
      tableData: [],
      tablePagination: {
        // tablePagination - options
        options: {
          total: 0,
          currentPage: 1,
          pageSize: 15,
          pageSizes: [15, 30, 50, 100],
          pagerCount: 5,
          isDisabled: false
        }
      },
      dialogAdd: {
        loading: false,
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        formData: {
          name: '',
          icon: '',
          iconColor: ''
        }
      },
      dialogEdit: {
        loading: false,
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        formData: {
          id: 0,
          name: '',
          icon: '',
          iconColor: ''
        }
      },
      dialogIcon: {
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: null,
        data: [
          'iconfont iconkucunguanli-01',
          'iconfont iconkehuguanli-01',
          'iconfont iconyingyongguanli-01',
          'iconfont iconzuzhijigou-01',
          'iconfont iconyonghuguanli-01',
          'iconfont iconjiaoseguanli-01',
          'iconfont iconweixiubaoyang-01',
          'iconfont iconzutaiguanli-01',
          'iconfont iconwumoxingguanli-01',
          'iconfont iconwangguanguanli-01',
          'iconfont iconshebeiguanli-01',
          'iconfont iconcaozuorizhi-01',
          'iconfont iconyujingtixing-01',
          'iconfont iconlishishuju-01',
          'iconfont iconshishishuju-01',
          'iconfont iconGISditu-01',
          'iconfont iconyingyongshangcheng-01'
        ],
        selected: null
      }
    };
  },
  mounted() {
    this.getTableData();
    window.onresize = () => {
      // 定义窗口大小变更通知事件
      this.tableHeightResize();
    };
    // 监听菜单栏的展开收起
    let sidebarEl = document.querySelector('.fold-icon');
    if (sidebarEl) {
      sidebarEl.addEventListener('click', () => {
        let myEvent = new Event('resize');
        window.dispatchEvent(myEvent);
      });
    }
  },
  computed: {
    iconColor() {
      return {
        add: `color: ` + this.dialogAdd.formData.iconColor,
        edit: `color: ` + this.dialogEdit.formData.iconColor
      };
    },
    addFormDataRules() {
      return {
        name: [
          { required: true, trigger: 'blur', message: this.$t('error.name') },
          { validator: this.validateName, trigger: 'blur', message: this.$t('error.nameLenth') }
        ]
        // icon: [{ required: true, trigger: 'change', message: this.$t('error.icon') }],
        // iconColor: [{ required: true, trigger: 'change', message: this.$t('error.iconColor') }]
      };
    },
    editFormDataRules() {
      return {
        name: [
          { required: true, trigger: 'blur', message: this.$t('error.name') },
          { validator: this.validateName, trigger: 'blur', message: this.$t('error.nameLenth') }
        ]
        // icon: [{ required: true, trigger: 'change', message: this.$t('error.icon') }],
        // iconColor: [{ required: true, trigger: 'change', message: this.$t('error.iconColor') }]
      };
    },
    button() {
      return {
        label: this.$t('btnText.addAppCategory'),
        type: 'primary',
        size: 'medium'
      };
    },
    tableConfig() {
      return {
        // table - options
        options: {
          height: this.tableMaxHeight,
          hasSelection: false,
          hasIndex: true,
          labelIndex: this.$t('table.labelIndex'),
          isStripe: false,
          isBorder: false,
          isHighlightCurrentRow: false,
          isInit: false,
          isLoading: false,
          sortable: true,
          labelSort: this.$t('table.labelSort'),
          headerRowStyle: ({ row, rowIndex }) => {
            return {};
          },
          headerCellStyle: ({ row, column, rowIndex }) => {
            return { padding: '8px 0' };
          },
          rowStyle: ({ row, rowIndex }) => {
            return {};
          },
          cellStyle: ({ row, column, rowIndex }) => {
            return { padding: '8px 0' };
          }
        },
        // table - columns
        columns: [
          // {
          //   prop: 'id',
          //   label: this.$t('table.columns_c.id'),
          //   width: 50,
          //   hasSort: false,
          //   isShow: true,
          //   fixed: 'left'
          // },
          {
            prop: 'name',
            label: this.$t('table.columns_c.name'),
            width: '',
            hasSort: false,
            isShow: true
          },
          {
            prop: 'icon',
            label: this.$t('table.columns_c.icon'),
            width: '',
            hasSort: false,
            isShow: true,
            columnFormatter: (row, column, value) => {
              return '<i class="' + value + '" style="color: ' + row.iconColor + '"></i>';
            }
          },
          {
            prop: 'total',
            label: this.$t('table.columns_c.appNum'),
            width: '',
            hasSort: false,
            isShow: true
          }
        ],
        // table - actions
        actions: {
          title: this.$t('table.columns_c.action'),
          width: 120,
          links: [
            {
              label: this.$t('table.btnText.edit'),
              type: 'primary',
              permission: 'ams:appCategoryManage:edit',
              handleLinkClick: row => {
                this.dialogEdit.visible = true;
                this.$nextTick(() => {
                  this.dialogEdit.formData.id = row.id;
                  this.dialogEdit.formData.name = row.name;
                  this.dialogEdit.formData.icon = row.icon;
                  this.dialogEdit.formData.iconColor = row.iconColor;
                });
              },
              handleLinkShow: row => {
                return true;
              },
              handleLinkDisabled: row => {
                return;
              }
            },
            {
              label: this.$t('table.btnText.del'),
              type: 'danger',
              permission: 'ams:appCategoryManage:delete',
              handleLinkClick: row => {
                this.submitDelete(row.id);
              },
              handleLinkShow: row => {
                let result = false;
                if (row.total === 0) {
                  result = true;
                }
                return result;
              },
              handleLinkDisabled: row => {
                return;
              }
            }
          ]
        }
      };
    }
  },
  methods: {
    validateName(rule, value, callback) {
      let myreg = /^[\u4e00-\u9fa50-9]{2,12}$/;
      if (!myreg.test(value)) {
        callback(new Error(this.$t('error.nameLenth')));
      }
      callback();
    },
    closeDialogAdd() {
      this.$refs['addCategory'].resetFields();
    },
    closeDialogEdit() {
      this.$refs['editCategory'].resetFields();
      this.dialogEdit.formData.id = 0;
    },
    closeDialogIcon() {
      this.dialogIcon.selected = null;
    },
    selectedIcon() {
      if (this.dialogIcon.type === 'add') {
        this.dialogAdd.formData.icon = this.dialogIcon.selected;
      } else if (this.dialogIcon.type === 'edit') {
        this.dialogEdit.formData.icon = this.dialogIcon.selected;
      }
      this.dialogIcon.visible = false;
    },
    handleDragSort(val) {
      let params = {
        id: this.tableData[val.oldIndex].id,
        sort: this.tableData[val.oldIndex].sort,
        nextId: this.tableData[val.newIndex].id,
        nextSort: this.tableData[val.newIndex].sort
      };
      categorySort(params).then(res => {
        this.getTableData();
      });
    },
    tableHeightResize() {
      if (this.$refs?.main?.clientHeight) {
        this.tableMaxHeight = this.$refs.main.clientHeight - 20 - 59 - 56;
        // 主内容区宽度
        let winInnerWidth = window.innerWidth;

        // 菜单栏宽度
        let sidebarWidth = document.querySelector('.sidebar-container').getBoundingClientRect().width;

        // 主内容区宽度
        let mainContentWidth = winInnerWidth - sidebarWidth - 30;
        mainContentWidth = mainContentWidth < 1030 ? 1030 : mainContentWidth;

        // 表格宽度
        let tableEl = document.querySelector('.el-table');
        tableEl.style.width = mainContentWidth - 40 + 'px';
      }
    },
    getTableData() {
      this.tableHeightResize();

      getCategorys({}).then(res => {
        this.tableAllData = res.data || [];
        let start = (this.tablePagination.options.currentPage - 1) * this.tablePagination.options.pageSize;
        let end = start + this.tablePagination.options.pageSize;
        this.tableData = this.tableAllData.slice(start, end);
        this.tablePagination.options.total = res.data.length;
      });
    },
    submitAdd(formName) {
      let _this = this;
      _this.$refs[formName].validate(valid => {
        if (valid) {
          categoryAdd(this.dialogAdd.formData).then(res => {
            this.dialogAdd.visible = false;
            this.$message.success(errorCode(res.message));
            this.getTableData();
          });
        } else {
          return false;
        }
      });
    },
    submitEdit(formName) {
      let _this = this;
      _this.$refs[formName].validate(valid => {
        if (valid) {
          categoryEdit(this.dialogEdit.formData).then(res => {
            this.dialogEdit.visible = false;
            this.$message.success(errorCode(res.message));
            this.getTableData();
          });
        } else {
          return false;
        }
      });
    },
    submitDelete(id) {
      this.$confirm(this.$t('warning.deleteAppCategory'), this.$t('warning.title'), {
        type: 'warning',
        confirmButtonText: this.$t('btnText.ok'),
        cancelButtonText: this.$t('btnText.cancel')
      })
        .then(() => {
          categoryDelete({ id: id }).then(res => {
            this.$message.success(errorCode(res.message));
            this.getTableData();
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.main-content {
  position: relative;
  padding: 20px;
}
.keepdown {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  width: auto !important;
}
.addbtn {
  margin-bottom: 20px;
  float: right;
}
.icon-box {
  width: 148px;
  height: 148px;
  border: 1px dashed #dcdfe6;
  box-sizing: border-box;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fafafa;
  background-image: url('../../assets/Union.png');
  background-repeat: no-repeat;
  background-position: center;
  padding: 15px;
}
.icon-content {
  display: inline-block;
  width: 100%;
  height: 100%;
  background-color: #fafafa;
  font-size: 116px;
}
.iconfont {
  line-height: 1;
  font-size: 100%;
}
.el-radio {
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 50px;
  height: 50px;
  vertical-align: middle;
  padding: 5px;
  margin-bottom: 30px;
}
::v-deep .el-radio .el-radio__input {
  display: none;
}
::v-deep .el-radio .el-radio__label {
  padding-left: 0;
}
::v-deep .el-radio .el-radio__label i {
  font-size: 40px;
}
.el-radio.is-checked {
  border-color: var(--color-primary);
  box-shadow: 0 0 5px var(--color-primary);
}
.special-form-item ::v-deep .el-form-item__label {
  width: 120px !important;
  margin-left: 80px;
  text-align: left;
  line-height: 28px;
}
.special-form-item ::v-deep .el-form-item__content {
  height: 28px;
  line-height: 28px;
}
</style>
